<?php
namespace app\index\controller;

use think\Controller;
use \think\Request;
use Firebase\JWT\JWT;

class Base extends Controller
{
	public $userid = '';

	public function _initialize()
    {
        $this->checkToken();
    }
    
    public function checkToken()
    {
        $header = Request::instance()->header();
        if (empty($header['authorization'])){
            echo json_encode([
                'status' => 1002,
                'msg' => 'Token不存在,拒绝访问'
            ]);
            exit;
        }else{
            $checkJwtToken = $this->verifyJwt(trim(str_ireplace('Bearer','',$header['authorization'])));
            if ($checkJwtToken['status'] == 1001) {
                return true;
            }
        }
    }
    
    //校验jwt权限API
    protected function verifyJwt($jwt)
    {
        $key = md5('xxxxxxx');
        JWT::$leeway = 60;
        try {
            $jwtAuth = json_encode(JWT::decode($jwt, $key, array('HS256')));
            $authInfo = json_decode($jwtAuth, true);
            $msg = [];
            if (!empty($authInfo['userid'])) {
            	$this->userid = $authInfo['userid'];
                $msg = [
                    'status' => 1001,
                    'msg' => 'Token验证通过'
                ];
            } else {
                $msg = [
                    'status' => 1002,
                    'msg' => 'Token验证不通过,用户不存在'
                ];
            }
            return $msg;
        } catch (\Firebase\JWT\SignatureInvalidException $e) {
        	$msg = [
                    'status' => 1003,
                    'msg' => 'Token无效'
                ];
            echo json_encode($msg);
            exit;
        } catch (\Firebase\JWT\ExpiredException $e) {
        	$msg = [
                    'status' => 1004,
                    'msg' => 'Token过期'
                ];
            echo json_encode($msg);
            exit;
        } catch (Exception $e) {
            return $e;
        }
    }

}
